<template>
  <div class="common-wrap">
    <div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane
          v-for="item in optionsTabs"
          :key="item.name"
          :label="$t(item.label)"
          :name="item.name"
        ></el-tab-pane>
      </el-tabs>
    </div>
    <div style="padding: 0 10px; height: calc(100% - 120px)">
      <keep-alive>
        <component
          :is="componentMap[activeName]"
          v-model:content="content"
          v-model:htmlContent="htmlContent"
          v-model:paperData="paperData"
          :tableData="tableData"
        />
      </keep-alive>
    </div>
    <div class="flex">
      <el-button type="default" @click="emitCloseEvent">
        {{ $t("取消") }}
      </el-button>
      <el-button :loading="saveBtnLoading" type="primary" @click="onSubmit">
        {{ $t("保存") }}
      </el-button>
    </div>
  </div>
</template>

<script setup >
import { onMounted, ref, watch } from "vue";
import editor from "./editor.vue";
import htmlPattern from "./htmlPattern.vue";
import htmlPreview from "./htmlPreview.vue";
import htmlPdf from "./htmlPdf.vue";
import { useRoute } from "vue-router";
import * as api from "@/api/index.js";
import { closeTag } from "@/utils/mUtils.js";
const route = useRoute();
defineOptions({
  name: "PrintDetails",
});
const content = ref("");
const editorContent = ref("");
const htmlContent = ref("");
const saveBtnLoading = ref(false);
const tableData = ref([]);
// 创建组件映射对象，将字符串名称映射到实际组件
const componentMap = {
  editor,
  htmlPattern,
  htmlPreview,
  htmlPdf,
};
const activeName = ref("editor");
const optionsTabs = [
  {
    label: "设计模板",
    name: "editor",
  },
  {
    label: "HTML模式",
    name: "htmlPattern",
  },
  {
    label: "HTML预览",
    name: "htmlPreview",
  },
  {
    label: "PDF预览",
    name: "htmlPdf",
  },
];
const paperData = ref({
  pageSizeType: "A4",
  direction: 1,
  marginTop: 1,
  marginLeft: 1,
  marginRight: 1,
  marginBottom: 1,
  pageWidth: 21.0,
  pageHeight: 29.7,
});
const directionObj = {
  0: "landscape",
  1: "portrait",
};
const formData = ref({});
const matchElement = () => {
  const regex = /<body[^>]*>([\s\S]*?)<\/body>/;
  const match = htmlContent.value.match(regex);
  // 只提取body标签内的内容，不包含body标签本身
  editorContent.value = match?.[1]?.trim() || "";
};
const insertElement = () => {
  // 使用正则表达式匹配body标签及其内容
  const page = `<style id="eprint_page_style">
      @page{size: ${paperData.value.pageSizeType || ""} ${
    directionObj[paperData.value.direction] || ""
  }; margin-top: ${paperData.value.marginTop || 0}cm; margin-bottom: ${
    paperData.value.marginBottom || 0
  }cm;margin-left:${paperData.value.marginLeft || 0}cm;margin-right:${
    paperData.value.marginRight || 0
  }cm;}</style>`;
  let str = `<!DOCTYPE html>
<html lang="zh-CN" xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta charset="UTF-8" />

    <style type="text/css">
      body {
          font-family: "AlibabaPuHuiTi-Light";
          font-size: 14px;
          word-break: break-all;
          word-wrap: break-word;
          background: #fff;
      }

      table {
          width: 100%;
          border-collapse: collapse;
          -fs-table-paginate: paginate;
          page-break-inside: auto;
      }

      tr {
          page-break-inside: auto;
          page-break-after: auto;
      }

      td, th {
          border-collapse: collapse;
      }

      p {
          margin: 0;
      }

      img {
          max-width: 100%;
          height: auto;
      }

      .page_break {
          page-break-after: always;
      }

      /* 新增样式：防止在最后一个元素后分页，避免末尾产生空白页 */
      .page_break:last-child {
          page-break-after: avoid;
      }
    </style>
    <style type="text/css">
      /** * 指定pdf纸张大小和页边距
       * 新增页码计数器和底部中央页码显示
       **/
      @page {
          size: A4;
          margin: 2cm;

          /* 初始化页码计数器，第一页将是1 */
      counter-reset: page 1;

          /* 在页面底部中央创建内容区域 */
          @bottom-center {
              content: counter(page); /* 显示页码 */
              font-family: "AlibabaPuHuiTi";
              font-size: 12px;
              color: #333;
          }
      }
    </style>
    <style id="rq_page_style">
      /** 指定pdf纸张大小 **/
      @page {
        size: A4;
        margin: 1cm;
      }
    </style>
  ${page}
  </head>
  <body>
    
  </body>
</html>`;
  const bodyRegex = /<body[^>]*>([\s\S]*?)<\/body>/;
  if (htmlContent.value) {
    // 先移除已存在的样式标签，避免重复插入
    str = htmlContent.value.replace(
      /<style id="eprint_page_style">[\s\S]*?<\/style>/g,
      page
    );
  }
  htmlContent.value = str.replace(
    bodyRegex,
    `<body>
      ${content.value || ""}
      </body>`
  );
};
watch(
  () => content.value,
  (newVal, oldVal) => {
    insertElement();
  },
  {
    immediate: true,
  }
);
watch(
  () => htmlContent.value,
  (newVal, oldVal) => {
    matchElement();
  }
);
watch(
  () => paperData.value,
  (newVal, oldVal) => {
    insertElement();
  },
  { deep: true }
);
const handleClick = (tab, value) => {
  if (activeName.value === "htmlPattern") {
    // 直接使用提取的body内容
    content.value = editorContent.value;
  }
};
onMounted(() => {
  getInfo();
});
const getInfo = async () => {
  const { data } = await api.default.common.printTemplate.getInfo(
    route.query.id
  );
  formData.value = data;
  paperData.value = {
    pageSizeType: data.pageSizeType || "A4",
    direction: data.direction,
    marginTop: data.marginTop,
    marginLeft: data.marginLeft,
    marginRight: data.marginRight,
    marginBottom: data.marginBottom,
    pageWidth: data.pageWidth || 21.0,
    pageHeight: data.pageHeight || 29.7,
  };
  htmlContent.value = data.templateContent || "";
  matchElement();
  content.value = editorContent.value;
  api.default.common.fieldConfiguration
    .getInfoByCode({
      code: data.moduleCode,
    })
    .then((res) => {
      tableData.value = res.data.fieldList;
      console.log(tableData);
    });
};
// 移除未使用的resizeTextarea函数
const emitCloseEvent = () => {
  if (route.query.title) {
    closeTag(route);
  }
};
const onSubmit = async () => {
  const parmas = {
    ...formData.value,
    ...paperData.value,
    templateContent: htmlContent.value,
  };
  // 编辑
  saveBtnLoading.value = true;
  api.default.common.printTemplate
    .edit(parmas)
    .then(() => {
      ElMessage.success("保存成功");
      saveBtnLoading.value = false;
      emits("onSubmit");
    })
    .catch(() => {
      saveBtnLoading.value = false;
    });
};
</script>

<style scoped lang="scss">
.maritimeAdd {
  width: 100%;
  height: 100%;
  background: #fff;

  .nav-title {
    font-size: 20px;
    color: #333;
    font-weight: 500;
    padding: 15px 10px 10px;
    border-bottom: 1px solid #e4e4e4;
  }
}
.flex {
  display: flex;
  justify-content: center;
  height: 53px;
  align-items: center;
}
</style>